package com.nl.model.model.form;

import com.nl.model.model.validate.ValidateGroup;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * 查询分页.
 *
 * @author xht.
 */
@Data
@EqualsAndHashCode
public class PagingForm implements Serializable {

    /**
     * 默认当前页.
     */
    public static final int DEFAULT_CURRENT_PAGE = 1;

    /**
     * 默认单页记录数.
     */
    public static final int DEFAULT_PAGE_SIZE = 10;

    /**
     * 最大分页行数.
     */
    public static final int MAX_PAGE_SIZE = 1000;

    /**
     * 分页起始位置.
     */
    @NotNull(message = "请输入分页起始位置", groups = {ValidateGroup.PaginationGroup.class})
    @ApiModelProperty(value = "当前页")
    private Integer pageNo;

    /**
     * 分页数据长度.
     */
    @NotNull(message = "请输入每页条数", groups = {ValidateGroup.PaginationGroup.class})
    @ApiModelProperty(value = "每页条数")
    private Integer pageSize;

    /**
     * 排序.
     */
    private SortBy sort;

    public PagingForm() {
    }

    public PagingForm(final int page, final int size) {
        this(page, size, null);
    }

    public PagingForm(final int page, final int size, final SortBy sort) {
        this.pageNo = (page <= 0) ? DEFAULT_CURRENT_PAGE : page;
        this.pageSize = (size <= 0 || size >= MAX_PAGE_SIZE) ? DEFAULT_PAGE_SIZE : size;
        this.sort = sort;
    }

    /**
     * 创建.
     *
     * @param page 当前页
     * @param size 每页行数
     * @return PageParam
     */
    public static PagingForm of(final int page, final int size) {
        return new PagingForm(page, size);
    }

    /**
     * 创建.
     *
     * @param page 当前页
     * @param size 每页行数
     * @param sort 排序
     * @return PageParam
     */
    public static PagingForm of(final int page, final int size, final SortBy sort) {
        return new PagingForm(page, size, sort);
    }

    /**
     * 起始行.
     *
     * @return int
     */
    public int getOffset() {
        return (getPage() - 1) * getSize();
    }

    /**
     * 当前页.
     *
     * @return int
     */
    public int getPage() {
        return pageNo <= 0 ? DEFAULT_CURRENT_PAGE : pageNo;
    }

    /**
     * 设置当前页.
     *
     * @param page 当前页
     */
    public void setPage(final int page) {
        this.pageNo = page;
    }

    /**
     * 每页数.
     *
     * @return int
     */
    public int getSize() {
        if (pageSize <= 0 || pageSize >= MAX_PAGE_SIZE) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        return pageSize;
    }

    /**
     * 设置每页数.
     *
     * @param size 每页数
     */
    public void setSize(final int size) {
        this.pageSize = size;
    }

    /**
     * 获取排序.
     *
     * @return SortBy
     */
    public SortBy getSort() {
        return sort;
    }

    /**
     * 设置排序.
     *
     * @param sort 排序属性
     */
    public void setSort(final SortBy sort) {
        this.sort = sort;
    }

}
